﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Wicresoft.Common;
using MonthlyDB.Entity;
using Monthly.Framework.BusinessLogic;

public partial class Page_EditMonthly : BaseAuthenticationPage
{
    protected DataTable AttachmentList
    {
        get
        {
            if (ViewState["AttachmentList"] == null)
            {
                ViewState["AttachmentList"] = new DataTable();
                (ViewState["AttachmentList"] as DataTable).Columns.Add("ID", typeof(Guid));
                (ViewState["AttachmentList"] as DataTable).Columns.Add("DisplayName", typeof(string));
                (ViewState["AttachmentList"] as DataTable).Columns.Add("PhysicalPath", typeof(string));
                (ViewState["AttachmentList"] as DataTable).Columns.Add("PhysicalUrl", typeof(string));
                (ViewState["AttachmentList"] as DataTable).Columns.Add("UploadTime", typeof(DateTime));
            }
            return ViewState["AttachmentList"] as DataTable;
        }
        set
        {
            ViewState["AttachmentList"] = value;
        }
    }
    protected string[] UserMonthlyTypes
    {
        get
        {
            if (ViewState["UserMonthlyTypes"] == null)
            {
                ViewState["UserMonthlyTypes"] = AppConfig.getUserTypes(CurrentUser.ID);
            }
            return ViewState["UserMonthlyTypes"] as string[];
        }
    }
    protected DataTable DelAttachment
    {
        get
        {
            if (ViewState["DelAttachment"] == null)
                ViewState["DelAttachment"] = new DataTable();
            return ViewState["DelAttachment"] as DataTable;
        }
        set
        {
            ViewState["DelAttachment"] = value;
        }
    }

    public Guid MonthlyID
    {
        get
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
                return new Guid(Request.QueryString["ID"]);
            return Guid.Empty;
        }
    }

    public string SearchClause
    {
        get
        {
            if (ViewState["SearchClause"] == null)
                ViewState["SearchClause"] = "1=1";
            return ViewState["SearchClause"].ToString();
        }
        set
        {
            ViewState["SearchClause"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        this.Title = "科室周报添加";
        tbPublishTime.Attributes.Add("readonly", "true");

        if (!IsPostBack)
        {
            if (AppConfig.getUserTypes(CurrentUser.ID).Length == 0)
            {
                Response.Clear();
                Response.Write("无权访问");
                Response.End();
            }
            else
            { 
                ddlType.DataSource = UserMonthlyTypes;
                ddlType.DataBind();
                ddlDept.DataSource = Wicresoft.Common.DataAccess.Select(typeof(Depts), "1=1", "DeptName desc");
                ddlDept.DataTextField = "DeptName";
                ddlDept.DataValueField = "ID";
                ddlDept.DataBind();

                if (MonthlyID != Guid.Empty)
                {
                    this.Title = "科室周报编辑";
                    MonthlyDB.Entity.Monthly monthly = new MonthlyDB.Entity.Monthly(MonthlyID);
                    monthly.Load();
                    
                    if (monthly.DeptID != Guid.Empty)
                    {
                        ListItem li = ddlDept.Items.FindByValue(monthly.DeptID.ToString());
                        if (li != null)
                            ddlDept.SelectedValue = li.Value;
                    }
                    ddlType.SelectedValue = monthly.Type;
                    tbSymbol.Text = monthly.Symbol;
                    tbFileName.Text = monthly.FileName;
                    tbKeywords.Text = monthly.Keywords;
                    tbPublishTime.Text = monthly.PublishTime.ToString("yyyy-MM-dd");
                    Content.Value = monthly.Content;
                    //先根据查询得到一个与AttendID对应的表AttendenceUser的一个集合
                    AttachmentList = BLMonthly.getAttachmentsByMonthlyID(MonthlyID);
                    DelAttachment = AttachmentList.Clone();
                    rptAttachList.DataSource = AttachmentList;
                    rptAttachList.DataBind();
                }
            }
        }
    }

    protected void lbtnSave_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(Content.Value))
        {
            ClientScript.RegisterStartupScript(GetType(), "wrong", "alert('必须填写科室周报正文');", true);
            return;
        }
        if (MonthlyID != Guid.Empty)
        {
            MonthlyDB.Entity.Monthly monthly = new MonthlyDB.Entity.Monthly(MonthlyID);
            monthly.Load();
            monthly.CreateTime = DateTime.Now;
            monthly.Creator = CurrentUser.Name;
            monthly.CreatorName = CurrentUser.DisplayName;
            monthly.FileName = tbFileName.Text;
            monthly.Keywords = tbKeywords.Text;
            monthly.PublishTime = DateTime.Parse(tbPublishTime.Text);
            monthly.Symbol = tbSymbol.Text;
            monthly.Content = Content.Value;
            monthly.Type = ddlType.SelectedValue;
            monthly.DeptID = new Guid(ddlDept.SelectedValue);
            monthly.Save();
            foreach (DataRow dr in AttachmentList.Rows)
            {
                Attachment attach = new Attachment();
                if (dr["ID"] != DBNull.Value && dr["ID"] != null)
                {
                    attach.ID = new Guid(dr["ID"].ToString());
                    attach.Load();
                }
                else
                {
                    attach.ID = Guid.NewGuid();
                }
                attach.MonthlyID = MonthlyID;
                attach.DisplayName = dr["DisplayName"].ToString();
                attach.PhysicalPath = dr["PhysicalPath"].ToString();
                attach.PhysicalUrl = dr["PhysicalUrl"].ToString();
                attach.UploadTime = DateTime.Now;
                attach.Save();
            }
            //从数据库中删除指定的附件
            BLMonthly.DeleteAttachments(DelAttachment);
        }
        else
        {
            MonthlyDB.Entity.Monthly monthly = new MonthlyDB.Entity.Monthly(Guid.NewGuid());
            monthly.CreateTime = DateTime.Now;
            monthly.Creator = CurrentUser.Name;
            monthly.CreatorName = CurrentUser.DisplayName;
            monthly.FileName = tbFileName.Text;
            monthly.Keywords = tbKeywords.Text;
            monthly.PublishTime = DateTime.Parse(tbPublishTime.Text);
            monthly.Symbol = tbSymbol.Text;
            monthly.Content = Content.Value;
            monthly.Type = ddlType.SelectedValue;
            monthly.DeptID = new Guid(ddlDept.SelectedValue);
            monthly.Add();

            foreach (DataRow dr in AttachmentList.Rows)
            {
                Attachment attach = new Attachment(Guid.NewGuid());
                attach.MonthlyID = monthly.ID;
                attach.DisplayName = dr["DisplayName"].ToString();
                attach.PhysicalPath = dr["PhysicalPath"].ToString();
                attach.PhysicalUrl = dr["PhysicalUrl"].ToString();
                attach.UploadTime = DateTime.Now;
                attach.Add();
            }
        }
        string script = "<script>alert('保存成功!');refreshParent();window.close();</script>";
        ClientScript.RegisterStartupScript(this.GetType(), "Close", script);
    }

    protected void rptAttachList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        switch (e.CommandName)
        {
            case "Delete":
                DelAttachment.ImportRow(AttachmentList.Rows[e.Item.ItemIndex]);

                AttachmentList.Rows.RemoveAt(e.Item.ItemIndex);    //内存中的条目删除            
                rptAttachList.DataSource = AttachmentList;
                rptAttachList.DataBind();
                break;
        }
    }
    protected void btnUpLoad_Click(object sender, EventArgs e)
    {
        if (upFile.PostedFile != null)
        {
            string fileName = upFile.PostedFile.FileName;
            string ext = System.IO.Path.GetExtension(fileName);
            string name = fileName.Substring(fileName.LastIndexOf(@"\") + 1, fileName.LastIndexOf(".") - fileName.LastIndexOf(@"\") - 1);
            Guid attachID = Guid.NewGuid();
            string PhysicalUrl = Request.ApplicationPath + "/Attachments/" + attachID + ext;
            string PhysicalPath = Server.MapPath(PhysicalUrl);
            DataRow dr = AttachmentList.NewRow();
            dr["ID"] = attachID;
            dr["DisplayName"] = name;
            dr["PhysicalPath"] = PhysicalPath;
            dr["PhysicalUrl"] = PhysicalUrl;
            dr["UploadTime"] = DateTime.Now;
            AttachmentList.Rows.Add(dr);
            upFile.PostedFile.SaveAs(PhysicalPath);
            rptAttachList.DataSource = AttachmentList;
            rptAttachList.DataBind();

        }
    }
}
